from .. import SendUnit
from typing import List
import time
import socket as sk


class Transmitter:
    """
    数据发送器
    """

    def __init__(self, dstip: str, dstport: int, data_sequence: List[SendUnit]):
        """
        数据发送器构造函数
        :param dstip: 发送的目标ip地址
        :param dstport: 发送的目标端口号
        :param data_sequence: 需要被发送的数据序列
        """
        self.dstip = dstip
        self.dstport = dstport
        self.data_sequence = data_sequence
        self.sender_cursor = 0
        self.tcp_client_socket = sk.socket(sk.AF_INET, sk.SOCK_STREAM)
        self.tcp_client_socket.connect((dstip, dstport))

    def send_data(self) -> SendUnit:
        data = self.data_sequence[self.sender_cursor]
        self.tcp_client_socket.send(data.get_data().encode("utf-8"))
        time.sleep(data.get_span())
        self.sender_cursor += 1
        if self.sender_cursor == len(self.data_sequence):
            # 发送数据完成
            self.tcp_client_socket.close()
        return data

    def is_finished(self) -> bool:
        return self.sender_cursor == len(self.data_sequence)
